package com.sr.util;

import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.beans.Introspector;
import java.io.Serializable;
import java.lang.invoke.SerializedLambda;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Function;
import java.util.regex.Pattern;

/**
 * @author xiaochi
 * @date 2021/12/2 17:18
 * @desc ToolUtil 工具类
 */
public class ToolUtil {

    private static IdWorker idWorker = new IdWorker(1,1);

    /**
     * 获取雪花算法id
     * @return
     */
    public static String nextId(){
        return String.valueOf(idWorker.nextId());
    }

    /**
     * 单个复制
     * @param source
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T>T copy(Object source,Class<T> clazz){
        if (source == null){
            return null;
        }
        T dest = null;
        try {
            dest = clazz.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        BeanUtils.copyProperties(source,dest);
        return dest;
    }

    /**
     * 集合复制
     * @param source
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> List<T> copy(List<?> source, Class<T> clazz){
        List<T> target = new ArrayList<>();
        if (!CollectionUtils.isEmpty(source)){
            for (Object c : source){
                target.add(copy(c,clazz));
            }
        }
        return target;
    }

    /**
     * length用户要求产生字符串的长度
     * @param length
     * @return
     */
    public static String getRandomString(int length){
        String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = ThreadLocalRandom.current();
        StringBuilder sb=new StringBuilder();
        for(int i=0;i<length;i++){
            int number=random.nextInt(62);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }

    /**
     * 通用脱敏方法（*显示，可用于：用户名，手机号，邮箱，地址等）
     * @param value
     * @return
     */
    private static final int SIZE = 6;
    private static final String SYMBOL = "*";
    public static String commonDisplay(String value) {
        if (null == value || "".equals(value)) {
            return value;
        }
        int len = value.length();
        int pamaone = len / 2;
        int pamatwo = pamaone - 1;
        int pamathree = len % 2;
        StringBuilder stringBuilder = new StringBuilder();
        if (len <= 2) {
            if (pamathree == 1) {
                return SYMBOL;
            }
            stringBuilder.append(SYMBOL);
            stringBuilder.append(value.charAt(len - 1));
        } else {
            if (pamatwo <= 0) {
                stringBuilder.append(value.substring(0, 1));
                stringBuilder.append(SYMBOL);
                stringBuilder.append(value.substring(len - 1, len));
            } else if (pamatwo >= SIZE / 2 && SIZE + 1 != len) {
                int pamafive = (len - SIZE) / 2;
                stringBuilder.append(value.substring(0, pamafive));
                for (int i = 0; i < SIZE; i++) {
                    stringBuilder.append(SYMBOL);
                }
                if ((pamathree == 0 && SIZE / 2 == 0) || (pamathree != 0 && SIZE % 2 != 0)) {
                    stringBuilder.append(value.substring(len - pamafive, len));
                } else {
                    stringBuilder.append(value.substring(len - (pamafive + 1), len));
                }
            } else {
                int pamafour = len - 2;
                stringBuilder.append(value.substring(0, 1));
                for (int i = 0; i < pamafour; i++) {
                    stringBuilder.append(SYMBOL);
                }
                stringBuilder.append(value.substring(len - 1, len));
            }
        }
        return stringBuilder.toString();
    }

    /**
     * 获取实体属性名称
     * @param fn
     * @param <T>
     * @return
     */
    private static final Pattern GET_PATTERN = Pattern.compile("^get[A-Z].*");
    private static final Pattern IS_PATTERN = Pattern.compile("^is[A-Z].*");
    public static  <T>String fnToFieldName(Fn<T,Object> fn){
        try {
            Method method = fn.getClass().getDeclaredMethod("writeReplace");
            method.setAccessible(true);
            SerializedLambda serializedLambda = ((SerializedLambda) method.invoke(fn));
            String name = serializedLambda.getImplMethodName();
            if (GET_PATTERN.matcher(name).matches()){
                name = name.substring(3);
            }else if (IS_PATTERN.matcher(name).matches()){
                name = name.substring(2);
            }
            return Introspector.decapitalize(name);
        }catch (ReflectiveOperationException e){
            throw new RuntimeException(e);
        }
    }
    public interface Fn<T,R> extends Function<T,R>, Serializable {}
}